<template>
    <el-drawer v-model='showDrawer'
               :title='drawerTitle'
               size='880px'
    >
        <el-form
            ref='formRef'
            label-position='left'
            :model='formData'
            label-width='98px'
            :rules='formRules'
            hide-required-asterisk
        >
            <el-form-item label='线路名称' prop='lineName'>
                <el-input v-model='formData.lineName' clearable placeholder='请输入线路名称' />
            </el-form-item>
            <el-form-item label='城市' prop='city'>
                <el-cascader
                    style='width:280px;' v-model='formData.city' :options='cityData'
                    @change='cityHandleChange' />
            </el-form-item>
            <el-form-item label='出发日期' prop='start_time'>
                <el-date-picker
                    v-model='formData.start_time'
                    type='datetime'
                    value-format='YYYY-MM-DD HH:mm:ss'
                    placeholder='请选择出发日期'
                    style='width: 280px'
                />
            </el-form-item>
            <el-form-item label='是否推荐'>
                <el-radio-group v-model='formData.is_tuijian'>
                    <el-radio :label='1'>是</el-radio>
                    <el-radio :label='0'>否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label='出游天数' prop='day'>
                <el-input type='number' v-model.number='formData.day' placeholder='请输入出游天数' />
            </el-form-item>
            <el-form-item label='住宿天数' prop='check_day'>
                <el-input type='number' v-model.number='formData.check_day' placeholder='请输入住宿天数' />
            </el-form-item>
            <el-form-item label='地址' prop='address'>
                <el-input v-model='formData.address' clearable placeholder='请输入地址' />
            </el-form-item>
            <el-form-item label='经纬度' prop='location'>
                <el-input v-model='formData.location' clearable
                          placeholder='请输入经纬度(直接将复制的经纬度粘贴到此处即可)'>
                    <template #append>
                        <el-button type='danger' @click='getLocation'>获取坐标</el-button>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label='价格' prop='money'>
                <el-input v-model='formData.money' clearable
                          placeholder='请输入价格'
                />
            </el-form-item>
            <el-form-item label='车型' prop='car_type'>
                <el-input type='text' v-model='formData.car_type' placeholder='请输入车型' />
            </el-form-item>
            <el-form-item label='出发地' prop='start_place'>
                <el-input type='text' placeholder='请输入出发地' v-model='formData.start_place' />
            </el-form-item>
            <el-form-item label='目的地' prop='end_place'>
                <el-input type='text' placeholder='请输入目的地' v-model='formData.end_place' />
            </el-form-item>
            <el-form-item label='简介' prop='introductory'>
                <el-input type='textarea' rows='5' v-model='formData.introductory' clearable placeholder='请输入简介' />
            </el-form-item>
            <el-form-item label='导游ID' prop='tourId'>
                <el-select v-model='formData.tourId' placeholder='请选择对应导游'>
                    <el-option v-for='(item,index) in guideOption' :key='index' :value='item.value'
                               :label='item.label' />
                </el-select>
            </el-form-item>
            <el-form-item label='推荐理由' prop='content'>
                <editor v-model='formData.content' :height='500' :width='720' />
            </el-form-item>
            <el-form-item label='景区游玩'>
                <el-input type='number' v-model='formData.spot_num' placeholder='请输入景点数量' />
            </el-form-item>
            <el-form-item label='户外活动'>
                <el-input type='number' v-model='formData.activity_num' placeholder='请输入自由活动数量' />
            </el-form-item>
            <el-form-item label='饮品小吃'>
                <el-input type='number' v-model='formData.catering_num' placeholder='请输入餐饮数量' />
            </el-form-item>
            <el-form-item label='特色体验'>
                <el-input type='number' v-model='formData.cost_num' placeholder='请输入自费项目数量' />
            </el-form-item>
            <el-form-item label='民宿酒店'>
                <el-input type='number' v-model='formData.shop_num' placeholder='请输入购物店数量' />
            </el-form-item>
            <el-form-item label='封面图' prop='cover_imag'>
                <material-picker :limit='1' v-model='formData.cover_imag' type='image' />
            </el-form-item>
            <el-form-item label='图片介绍' prop='files'>
                <material-picker :limit='10' v-model='formData.files' type='image' />
            </el-form-item>
            <el-form-item label='视频介绍'>
                <material-picker :limit='3' v-model='formData.videos' type='video' />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-space>
                <el-button type='info' plain>取消操作</el-button>
                <el-button type='primary' @click='confirmHandle' :loading='loading'>{{
                        formData.isEdit ? '确认编辑' : '提交保存'
                    }}
                </el-button>
            </el-space>
        </template>
    </el-drawer>
</template>

<script lang='ts' setup name='productLineEdit'>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProductLineAdd, apiProductLineEdit, apiProductLineDetail, apiAllGuide } from '@/api/product_line'
import type { PropType } from 'vue'
import { computed } from 'vue'
import { getCity, getCityNew } from '@/api/article'

const props = defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    },
    modelValue: {
        type: Boolean,
        required: true
    }
})
const cityData = ref<any>([])
initCityData()

function cityHandleChange(ev: any) {
    formData.city = ev
}

function resetForm() {
    formRef.value?.resetFields()
    const arrayKey = ['files', 'videos']
    for (const key in formData) {
        if (arrayKey.includes(key)) {
            formData[key] = []
        } else {
            formData[key] = ''
        }
    }
    formData.isEdit = false
}

watch(() => props.modelValue, value => {
    if (!value) return resetForm()
    initGuideUser()
})


async function initCityData() {
    const resp = await getCityNew({})
    if (!resp || !resp.length) return

    function patchMap(v: any) {
        if (!v.hasOwnProperty('children')) return
        if (!v.children || !v.children.length) return
        return v.children.map((item: any) => {
            const { id, name, merger_name } = item
            const data = {
                value: id, label: name, fullName: merger_name
            }
            const children = patchMap(item)
            if (children) data.children = children
            return data
        })
    }

    cityData.value = resp.map((item: any) => {
        const { id, name, merger_name: fullName } = item
        return {
            label: name, value: id, children: patchMap(item), fullName
        }
    })
    console.log(cityData.value, 'cityData')
}

const loading = ref(false)
// 表单数据
const formData = reactive<any>({
    id: '',
    lineName: '',
    city: [],
    address: '',
    location: '',
    lng: '',
    lat: '',
    money: '',
    introductory: '',
    content: '',
    tourId: '',
    files: [],
    videos: [],
    isEdit: false,
    spot_num: '',
    activity_num: '',
    catering_num: '',
    cost_num: '',
    shop_num: '',
    cover_imag: '',
    start_time: '',
    day: '',
    car_type: '',
    start_place: '',
    end_place: '',
    check_day: '',
    is_tuijian: 1
})


function getEndTime(timeStr: string, dayCount: number) {
    const startDate = new Date(timeStr)
    const date = new Date(startDate.setDate(startDate.getDate() + dayCount))

    function patchZero(value: number) {
        return ('0' + value).slice(-2)
    }

    const [year, month, day, hour, minute, seconds] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()]
    return `${year}-${patchZero(month)}-${patchZero(day)} ${patchZero(hour)}:${patchZero(minute)}:${patchZero(seconds)}`
}

function formatFormData() {
    const {
        lineName: line_name, address, location, money, introductory, tourId, content, files, videos, city,
        spot_num,
        activity_num,
        catering_num,
        cost_num,
        shop_num,
        cover_imag,
        day,
        car_type,
        start_place,
        end_place,
        start_time,
        check_day,
        is_tuijian
    } = formData
    const [lat, lng] = location.split(',')
    const source = [
        ...files.map((item: string) => ({
            url: item,
            type: 0
        })),
        ...videos.map((item: string) => ({
            url: item,
            type: 1
        }))
    ]
    const end_time = getEndTime(start_time, day * 1)
    const payload = {
        line_name,
        addr: address,
        lng, lat, money, introductory, content, tour_id: tourId,
        city_id: city,
        source, spot_num,
        activity_num,
        catering_num,
        cost_num,
        shop_num,
        cover_image: [cover_imag],
        day,
        car_type,
        start_place,
        end_place,
        start_time,
        end_time,
        check_day,
        is_tuijian
    }
    if (formData.isEdit) {
        payload.id = formData.id
    }
    return payload
}

const guideOption = ref([])

async function initGuideUser() {
    const list = await apiAllGuide()
    if (!!list && list.length) {
        guideOption.value = list.map((item: any) => {
            const { id: value, name: label } = item
            return { label, value }
        })
    }
}

// 表单验证
const formRules = computed(() => ({
    lineName: [
        {
            required: true,
            message: '请输入线路名称',
            trigger: 'blur'
        }
    ],
    city: [
        {
            required: true,
            message: '请选择对应城市',
            trigger: 'change'
        }
    ],
    address: [
        {
            required: true,
            message: '请输入线路地址',
            trigger: 'blur'
        }
    ],
    location: [
        {
            required: true,
            message: '请输入经纬度',
            trigger: 'blur'
        },
        {
            validator: (rules: any, value: string, callback: any) => {
                if (!value) return callback(new Error('请输入经纬度'))
                const locationArr = value.split(',')
                if (!locationArr || !Array.isArray(locationArr) || locationArr.length !== 2) return callback(new Error('经纬度使用英文输入法的逗号分隔'))
                const [lng, lat] = locationArr
                if (!lng || !lat) return callback(new Error('请输入合法的经纬度'))
                callback()
            },
            trigger: 'blur'
        }
    ],
    money: [
        {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
        }
    ],
    introductory: [
        {
            required: true,
            message: '请输入线路介绍',
            trigger: 'blur'
        }
    ],
    tourId: [
        {
            required: true,
            message: '请输入导游ID',
            trigger: 'blur'
        }
    ],
    content: [
        {
            required: true,
            message: '请输入推荐理由、产品特色',
            trigger: 'change'
        }
    ],
    files: [
        {
            required: true,
            message: '请上传线路图片',
            trigger: ['blur', 'change']
        }
    ],
    cover_imag: [
        {
            required: true,
            message: '请上传封面图',
            trigger: 'blur'
        }
    ],
    start_time: [
        {
            required: true,
            message: '请选择出游日期',
            trigger: 'blur'
        }
    ],
    day: [
        {
            required: true,
            message: '请输入出游天数',
            trigger: 'blur'
        }
    ],
    start_place: [
        {
            required: true,
            message: '请输入出发地',
            trigger: 'blur'
        }
    ],
    end_place: [
        {
            required: true,
            message: '请输入目的地',
            trigger: 'blur'
        }
    ],
    check_day: [
        {
            required: true,
            message: '请输入住宿天数',
            trigger: 'blur'
        }
    ]
}))

function reqMethod(data: any) {
    if (formData.isEdit) return apiProductLineEdit(data)
    return apiProductLineAdd(data)
}

function confirmHandle() {
    formRef.value?.validate().then(async () => {
        loading.value = true
        const payload = formatFormData()
        await reqMethod(payload)
        loading.value = false
        emit('success')
        emit('close')
    }).catch(() => {
    })
}

function getLocation() {
    window.open('https://lbs.qq.com/getPoint/')
}

const drawerTitle = ref('添加线路')

const emit = defineEmits(['success', 'close', 'update:modelValue'])
const showDrawer = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emit('update:modelValue', value)
    }
})
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑线路管理' : '新增线路管理'
})

// 获取详情
/**
 * id: '',
 *   lineName: '',
 *   city: '',
 *   address: '',
 *   location: '',
 *   lng: '',
 *   lat: '',
 *   money: '',
 *   introductory: '',
 *   content: '',
 *   tourId: '',
 *   files: [],
 *   videos: [],
 * @param data
 */
const setFormData = (data: Record<any, any>) => {
    const {
        addr, city_id, content, line_name, lat, lng, tour_id,
        money, introductory,
        slideshow, id, cover_image, start_time, day, start_place, end_place, car_type, check_day, province, area
    } = data
    const {
        spot_num,
        activity_num,
        catering_num,
        cost_num,
        shop_num,
        is_tuijian
    } = data
    formData.address = addr
    formData.city = [province, city_id, area]
    formData.lineName = line_name
    formData.content = content
    formData.location = `${lat},${lng}`
    formData.money = money
    formData.tourId = tour_id
    formData.introductory = introductory
    formData.isEdit = true
    formData.id = id
    formData.spot_num = spot_num
    formData.cost_num = cost_num
    formData.shop_num = shop_num
    formData.catering_num = catering_num
    formData.activity_num = activity_num
    formData.cover_imag = cover_image
    formData.car_type = car_type
    formData.start_place = start_place
    formData.end_place = end_place
    formData.start_time = start_time
    formData.day = day
    formData.check_day = check_day
    formData.is_tuijian = is_tuijian * 1
    if (!!slideshow && slideshow.length) {
        formData.files = slideshow.filter((item: any) => {
            return item.type * 1 === 0
        }).map((item: any) => item['image_video'])
        formData.videos = slideshow.filter((item: any) => {
            return item.type * 1 === 1
        }).map((item: any) => item['image_video'])
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiProductLineDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit'
        ? await apiProductLineEdit(data)
        : await apiProductLineAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
